<template>
  <MainSlot v-loading="loading">
    <template v-slot:searchForm>
      <SearchForm :formItemList="formItemList" @search="search"></SearchForm>
    </template>
    <template v-slot:table>
      <baidu-map v-if="retSetMap" class="map" :center="center" :zoom="zoom" :scroll-wheel-zoom="true"
        map-type="BMAP_HYBRID_MAP">
        <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT" />
        <BmlMarkerClusterer :average-center="true">
          <bm-marker v-for="(item, index) in groupLngLatArr" :key="index + 9999999999" :position="{
    lng: item.center.lng - 0.000003,
    lat: item.center.lat - 0.000043,
  }" :dragging="false">
            <bm-label :content="item[0].title.facilityName" :label-style="labelStyle"
              :offset="{ width: -5, height: 15 }" @click="infoMultipleOpen(item)" />
          </bm-marker>
        </BmlMarkerClusterer>
        <bm-info-window :position="{ lng: lngLatCore.lng, lat: lngLatCore.lat }" :show="infoWindow.show"
          @close="infoWindowClose">
          <span class="BMap_bubble_title">设施信息</span>
          <p><span>设施类型:</span> {{ lngLatArrform.facilityTypeName }}</p>
          <p><span>设施组:</span> {{ lngLatMultipleform.groupName }}</p>
          <p><span>设施名称:</span> {{ lngLatArrform.facilityName }}</p>
          <!-- <p><span>承租户:</span> {{ lngLatArrform.lesseeName }}</p> -->
          <p><span>农业类型:</span> {{ lngLatArrform.farmingTypeName }}</p>
          <!-- <p><span>主要种养品种:</span> {{ lngLatArrform.plantingTypeName }}</p> -->
          <p><span>地址:</span> {{ lngLatArrform.address }}</p>
          <p><span>面积: </span> {{ lngLatArrform.scope }} 亩</p>
        </bm-info-window>
        <bm-polygon :path="lngLatArr" stroke-color="#ffdb5c" fill-color="#ffdb5c" :stroke-opacity="1"
          :fill-opacity="0.4" :stroke-weight="3" :editing="jkedit" @click="infoWindowOpen(lngLatArr)"
          @mouseout="infoWindowOot" />
        <div v-for="(item, index) in groupLngLatArr" :key="index">
          <bm-polygon :path="item" stroke-color="#03F5EC" fill-color="#00fff6" :stroke-opacity="1" :fill-opacity="0.2"
            :stroke-weight="3" :editing="jkedit" @click="infoMultipleOpen(item)" @mouseout="infoMultipleOot" />
        </div>
        <bm-info-window :position="{
    lng: lngLatMultipleCore.lng,
    lat: lngLatMultipleCore.lat,
  }" :show="infoMultiple.show" @close="infoMultipleClose">
          <span class="BMap_bubble_title">设施信息</span>
          <p>
            <span>设施类型:</span> {{ lngLatMultipleform.facilityTypeName }}
          </p>
          <p><span>设施组:</span> {{ lngLatMultipleform.groupName }}</p>
          <p><span>设施名称:</span> {{ lngLatMultipleform.facilityName }}</p>
          <!-- <p><span>承租户:</span> {{ lngLatMultipleform.lesseeName }}</p> -->
          <!-- <p><span>农业类型:</span> {{ lngLatMultipleform.farmingTypeName }}</p> -->
          <p>
            <span>主要种养品种:</span>
            {{ lngLatMultipleform.plantingTypeName }}
          </p>
          <p><span>地址:</span> {{ lngLatMultipleform.address }}</p>
          <p><span>面积: </span>{{ lngLatMultipleform.scope }} 亩</p>
        </bm-info-window>
      </baidu-map>
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components/MainSlot";
import SearchForm from '@/components/SearchForm';
import facilityManagement from '@/api/digtalOperation/facilityManagement';
import BtnSlot from '@/components/BtnSlot';
import { BmlMarkerClusterer } from "vue-baidu-map";
export default {
  components: { MainSlot, SearchForm, BtnSlot, BmlMarkerClusterer },
  data() {
    return {
      retSetMap: true,
      loading: false,
      center: { lng: 120.230648, lat: 30.811543 },
      jkedit: false,
      zoom: 17,
      lngLatCore: {},
      groupLngLatArr: [],
      infoWindow: {
        show: false
      },
      infoMultiple: {
        show: false
      },
      lngLatArr: [],
      addEditFlag: 'add',
      btnList: ['add', 'delete'],
      formData: {},
      detailsInfo: {},
      searchFormData: {},
      lngLatArrform: {},
      lngLatCore: {},
      infoMultiple: {
        show: false
      },
      facilityGName: "",
      lngLatMultipleform: {},
      lngLatMultipleCore: {},
      labelStyle: {},
      formItemList: [
        {
          label: '设施组',
          type: 'select',
          selectOptions: this.setOptions('facilityGroupNo'),
          param: 'facilityGroupNo',
          defaultSelect: '',
          multiple: false,
          isShow: true
        },
        {
          label: '设施',
          type: 'select',
          selectOptions: this.setOptions('facilityNo'),
          param: 'facilityNo',
          defaultSelect: '',
          multiple: false,
          isShow: true
        }
      ]
    }
  },
  computed: {
    allFacility() {
      return this.$store.state.initData.allFacility || [];
    },
    organizationInfo() {
      return this.$store.state.initData.organizationInfo || [];
    },
    lessesList() {
      return this.$store.state.initData.lessesList || [];
    },
  },
  mounted() {
    this.facilityPointList();
  },
  methods: {
    infoWindowOpen(e) {
      if (e) {
        this.lngLatCore = this.getCenterPoint(e);
        this.lngLatArrform = Object.assign(e[0].title);
        setTimeout(() => {
          this.infoWindow.show = true;
          // this.getdatatime()
        }, 100);
      }
    },
    infoMultipleOpen(e) {
      if (e) {
        this.lngLatMultipleCore = this.getCenterPoint(e);
        this.lngLatMultipleform = Object.assign(e[0].title);
        setTimeout(() => {
          this.infoMultiple.show = true;
        }, 100);
      }
    },
    // 信息窗体
    infoWindowClose(e) {
      this.infoWindow.show = false;
    },
    infoWindowOot(e) {
      this.infoWindow.show = false;
    },
    // 信息窗体
    infoMultipleClose(e) {
      this.infoMultiple.show = false;
    },
    infoMultipleOot(e) {
      this.infoMultiple.show = false;
    },
    // 设施下拉框改变时
    async facilityChange(val) {
      if (!val) {
        this.lngLatArr = [];
        this.infoWindow.show = false;
        this.infoMultiple.show = false;
        this.search();
        return;
      }
      this.lngLatArr = [];
      this.infoWindow.show = false;
      this.infoMultiple.show = false;
      const { data: res } = await facilityManagement.queryByNo(val);
      let facilityPointList = res.facilityPointList || [];
      if (facilityPointList.length) {
        facilityPointList.forEach((item) => {
          const obj = {};
          obj["lng"] = item.axisY;
          obj["lat"] = item.axisX;
          obj["title"] = res;
          this.lngLatArr.push(obj);
        });
        this.$nextTick(() => {
          this.center = {
            lng: this.lngLatArr[0].lng,
            lat: this.lngLatArr[0].lat
          };
        });
      } else {
        return this.$message.warning("暂无设施信息");
      }
    },
    async facilityGroupChange(val) {
      if (!val) {
        this.groupLngLatArr = [];
        this.infoWindow.show = false;
        this.infoMultiple.show = false;
        this.lngLatArr = [];
        this.facilityNo = "";
        this.search();
        this.facilityPointList();
        return;
      }
      this.groupLngLatArr = [];
      this.lngLatArr = [];
      this.infoWindow.show = false;
      this.infoMultiple.show = false;
      const { data: resp } = await facilityManagement.queryFacilityGroup(val);
      let facilityGroupArr = resp;
      if (facilityGroupArr) {
        let facilityG = [];
        facilityGroupArr.forEach((itemthree) => {
          if (itemthree.facilityPointList) {
            facilityG.push(itemthree);
          }
        });
        if (facilityG.length > 0) {
          let lngLatAll = [];
          facilityG.forEach(async (itemthree) => {
            let facilityPointList = itemthree.facilityPointList || [];
            // 获取 百度地图 经纬度
            let lngLatArr = [];
            facilityPointList.forEach((item) => {
              const obj = {};
              obj["lng"] = item.axisY;
              obj["lat"] = item.axisX;
              obj["title"] = itemthree;
              lngLatArr.push(obj);
              lngLatAll.push(obj);
            });
            this.groupLngLatArr.push(lngLatArr);
            this.groupLngLatArr.forEach((item) => {
              item["center"] = this.getCenterPoint(item);
            });
          });
          let center = this.getCenterPoint(lngLatAll);
          if (lngLatAll.length) {
            this.retSetMap = false
            this.$nextTick(() => {
              this.retSetMap = true
              this.center = {
                lng: center.lng,
                lat: center.lat
              };
              console.log(this.center)
              if (this.groupLngLatArr.length > 100) {
                this.zoom = 16;
                this.labelStyle.fontSize = "12px";
              } else if (
                this.groupLngLatArr.length > 60 &&
                this.groupLngLatArr.length < 100
              ) {
                this.zoom = 17;
                this.labelStyle.fontSize = "14px";
              } else if (
                this.groupLngLatArr.length > 30 &&
                this.groupLngLatArr.length < 60
              ) {
                this.zoom = 18;
                this.labelStyle.fontSize = "16px";
                this.labelStyle.transform = "translateX(-15%)";
              } else if (this.groupLngLatArr.length < 30) {
                this.zoom = 19;
                this.labelStyle.fontSize = "18px";
                this.labelStyle.transform = "translateX(0%)";
              }
            });
          }
        } else {
          this.$message.warning("暂无设施组信息");
        }
      }
      if (val) {
        this.facilityNo = "";
        this.facilityArr = facilityGroupArr;
      }
    },
    // 查询所有设施信息
    facilityPointList() {
      let resp = this.allFacility
      this.groupLngLatArr = [];
      let list = [];
      list = resp;
      this.facilityArr = resp;
      let lngLatAll = [];
      list.forEach((itemthree) => {
        if (itemthree.facilityPointList) {
          let lngLatArr = [];
          let facilityGroupArr = itemthree.facilityPointList;
          facilityGroupArr.forEach((item) => {
            const obj = {};
            obj["lng"] = item.axisY;
            obj["lat"] = item.axisX;
            obj["title"] = itemthree;
            lngLatArr.push(obj);
            lngLatAll.push(obj);
          });
          this.groupLngLatArr.push(lngLatArr);
          this.groupLngLatArr.forEach((item) => {
            item["center"] = this.getCenterPoint(item);
          });
        }
      });
      let center = this.getCenterPoint(lngLatAll);
      if (lngLatAll.length) {
        this.$nextTick(() => {
          this.center = {
            lng: center.lng || 120.230648,
            lat: center.lat || 30.811543
          };
          if (this.groupLngLatArr.length >= 100) {
            this.zoom = 16;
            this.labelStyle.fontSize = "12px";
          } else if (
            this.groupLngLatArr.length >= 60 &&
            this.groupLngLatArr.length < 100
          ) {
            this.zoom = 17;
            this.labelStyle.fontSize = "12px";
          } else if (
            this.groupLngLatArr.length >= 15 &&
            this.groupLngLatArr.length < 60
          ) {
            this.zoom = 18;
            this.labelStyle.fontSize = "14px";
            this.labelStyle.transform = "translateX(-15%)";
          } else if (this.groupLngLatArr.length < 15) {
            this.zoom = 18;
            this.labelStyle.fontSize = "16px";
            this.labelStyle.transform = "translateX(0%)";
          }
        });
      } else {
        let onInfo = this.organizationInfo;
        console.log(onInfo)
        if (onInfo) {
          this.$set(this.center, "lng", onInfo.longitude || 120.230648);
          this.$set(this.center, "lat", onInfo.latitude || 30.811543);
        }
      }

      console.log(this.center)
    },
    // 计算多边形中心点
    getCenterPoint(data) {
      let lng = 0.0;
      let lat = 0.0;
      // console.log(data)
      for (let point of data) {
        // console.log(point)
        lat += JSON.parse(point["lat"]);
        lng += JSON.parse(point["lng"]);
      }
      lng = lng / data.length + 0.000084;
      lat = lat / data.length + 0.000014;
      // console.log(lng, lat, data.length + 0.000084, data.length + 0.000014);
      return { lng: lng, lat: lat };
    },
    setOptions(param) {
      let options = [];
      if (param == 'stordocNo') {
        this.$store.state.initData.stordoc.forEach(item => {
          options.push(
            { text: item.stordocName, value: item.stordocNo }
          )
        })
      } else if (param == 'facilityNo') {
        this.$store.state.initData.allFacility.forEach(item => {
          options.push(
            { text: item.facilityName, value: item.facilityNo }
          )
        })
      } else if (param == 'lesseeNo') {
        console.log(this.$store.state.initData.lessesList)
        this.$store.state.initData.lessesList.forEach(item => {
          options.push(
            { text: item.lesseeName, value: item.lesseeNo }
          )
        })
      } else if (param == 'facilityGroupNo') {
        console.log(this.$store.state.initData.facilityGroup)
        this.$store.state.initData.facilityGroup.forEach(item => {
          options.push(
            { text: item.facilityGroupName, value: item.facilityGroupNo }
          )
        })
      }
      return options;
    },
    async queryFacilityGroupList(e) {
      const { data: res } = await facilityManagement.getfacilityGroupAll({ lesseeNo: e || undefined });
      this.facilityGroupArr = res;
    },
    // 条件查询所有设施信息
    async getFacilityListByConditionAll(e) {
      let params = {
        facilityStatus: false,
        lesseeNo: e
      };
      const { data: resp } = await facilityManagement.getFacilityListByConditionAll(params);
      this.facilityArr = resp;
    },
    search(data) {
      this.searchFormData = { ...this.searchFormData, ...data };
      this.facilityPointList();
      if (this.searchFormData.facilityGroupNo) {
        this.facilityGroupChange(this.searchFormData.facilityGroupNo)
      } else if (this.searchFormData.facilityNo) {
        this.facilityChange(this.searchFormData.facilityNo)
      } else if (this.searchFormData.lesseeNo) {
        this.queryFacilityGroupList(this.searchFormData.lesseeNo)
        this.getFacilityListByConditionAll(this.searchFormData.lesseeNo)
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.map {
  width: 100%;
  height: 100%;
}
</style>